<?php
if (!defined("APP_PATH")) {
    define('APP_PATH',__DIR__.'/../application/');
    // 加载框架引导文件
    require  __DIR__.'/../thinkphp/start.php';
}

use think\Db;
use think\Exception;
use think\Log;
use fast\Http;

echo "<pre>";
set_time_limit(0);
//每小时触发一次 小区业绩奖励

if(config("site.pv_switch")) {
    get_pv_result();
} else {
    echo '未开启小区业绩奖励：'.date('Y-m-d H:i:s')."\r\n";exit;
}
function get_pv_result()
{
    $debug = config("app_debug");
    if (php_sapi_name() != 'cli' && !$debug) {
        // echo '只能在cli模式下或者开启调试模式运行：' . date('Y-m-d H:i:s') . "\r\n";die;
    }
    echo '开始执行的时间：'.date('Y-m-d H:i:s')."\r\n";
    $redis = rds();
    $bkey = REDIS_PREFIX.'get_pv_result';
    if($debug) {
        delkey($redis,$bkey);
    }
    $op = $redis->set($bkey,1,['NX','EX'=>3590]);
    if(!$op){
        echo '请勿频繁操作：'.date('Y-m-d H:i:s')."\r\n";
        goto END1;
    }

    //$hour = intval(date('H'));//当天 时
    //$pv_key = REDIS_PREFIX.'pv';

    $users = \db('user')->alias('u')
        ->field('u.id,ud.tjid,u.credit1,u.pv,u.pv_sum')
        ->join('user_detail ud', 'u.id = ud.uid')
        ->where(['u.credit1'=>['>',0]])
        ->select();

    $award_arr = [];
    $bili_arr = [];
    if (empty($users)) {
        echo "\r\n".'暂无数据：'.date('Y-m-d H:i:s')."\r\n";
        goto END2;
    }
    $i = 0;
    foreach ($users as $key => $value) {
        //判断0点更新redis小区业绩
        $pv = 0;
   
        //用户小区业绩 需要用户投资时给上级链用户增加业绩字段
        $users[$key]['team_pv'] = [];
        foreach ($users as $key1 => $value1) {
            if ($users[$key]['id'] == $value1['tjid']) {
                $users[$key]['team_pv'][$value1['id']] = $value1['pv_sum'];
            }
        }
        if ($users[$key]['team_pv']) {
            $posi = array_search(max($users[$key]['team_pv']), $users[$key]['team_pv']);
            unset($users[$key]['team_pv'][$posi]);
            $users[$key]['team_pv_sum'] = array_sum($users[$key]['team_pv']);
            $pv = $users[$key]['team_pv_sum'];
        }

        //小于200不足0.1%
        if ($pv < 200) {
            continue;
        }
        //得出最大奖金比例
        $bi = bcmul(bcdiv($pv, 200, 6), 0.001, 6);
        $bi = $bi > 0.1 ? 0.1 : $bi;
        $bili_arr['user_'.$value['id']] = $bi*100;
        $award = bcmul($users[$key]['credit1'], $bi, 6); //总发放数
        $award_arr['user_'.$value['id']] = $award;
        $i++;
    }
    if (empty($award_arr)) {
        echo "\r\n".'无可发放奖励用户：'.date('Y-m-d H:i:s')."\r\n";
        goto END2;
    }
    $redis->hMset(REDIS_PREFIX.'user_pv_bili',$bili_arr); //小区比例
    $redis->hMset(REDIS_PREFIX.'user_pv',$award_arr);//小区总发放数
    if (empty($redis->hGetAll(REDIS_PREFIX.'user_pv'))) {
        echo "\r\n".'小区业绩奖励user_pv--redis错误：'.date('Y-m-d H:i:s')."\r\n";
        delkey($redis,$bkey);
        goto END1;
    }
    if (empty($redis->hGetAll(REDIS_PREFIX.'user_pv_bili'))) {
        echo "\r\n".'小区业绩奖励user_pv_bili--redis错误：'.date('Y-m-d H:i:s')."\r\n";
        delkey($redis,$bkey);
        goto END1;
    }
    $day = date('Ymd');
    $lua = <<<LUA
    local all_user_pv = redis.call('hGetALL',KEYS[1])
    local i = 1
    local key
    if all_user_pv ~= false
    then
        for k,vel in ipairs(all_user_pv) do
            if i%2==0
            then
                local add_sy = vel
                local day_sy = redis.call('hGet',KEYS[3],key)
                if day_sy == false
                then
                    redis.call('hIncrByFloat',KEYS[2],key,add_sy)
                    redis.call('hIncrByFloat',KEYS[3],key,add_sy)
                    redis.call('hIncrByFloat',KEYS[5],key,add_sy)
                else
                    local new_sy = day_sy + add_sy
                    local max_sy = redis.call('hGet',KEYS[4], key)*0.1
                    day_sy = day_sy*1
                    if day_sy < max_sy
                    then
                        if new_sy <= max_sy
                        then
                            redis.call('hIncrByFloat',KEYS[2],key,add_sy)
                            redis.call('hIncrByFloat',KEYS[3],key,add_sy)
                            redis.call('hIncrByFloat',KEYS[5],key,add_sy)
                        else
                            local add_sy = max_sy - day_sy
                            redis.call('hIncrByFloat',KEYS[2],key,add_sy)
                            redis.call('hSet',KEYS[3],key,max_sy)
                            redis.call('hIncrByFloat',KEYS[5],key,add_sy)
                        end
                    end
                end
            else
                key = vel
            end
            i = i + 1
        end
    end
    return true
LUA;
    $ret = $redis->eval($lua,[REDIS_PREFIX.'user_pv',REDIS_PREFIX.'user_sy',REDIS_PREFIX.$day.'_sy',REDIS_PREFIX.'user_tz', REDIS_PREFIX.'static_sy'],5);
    if($ret === false){
        echo '执行失败：'.date('Y-m-d H:i:s')."\r\n";
        delkey($redis,$bkey);
        goto END1;
    }
    END2:
    /*//判断0点更新小区业绩
    if($hour == 0){
        $redis->del(REDIS_PREFIX.'user_pv');
        $redis->del(REDIS_PREFIX.'user_pv_bili');
        \db('user')->where('1=1')->update(['pv' => 0]);
    }*/
    delkey($redis,$bkey);
    END1:
    echo "\r\n".'结束执行的时间：'.date('Y-m-d H:i:s')."\r\n";
}


